import { watch, onBeforeUnmount, onDeactivated } from "vue";
import { getScrollParent, onMountedOrActivated } from "@vant/use";
import { useTouch } from "./use-touch.mjs";
import { preventDefault } from "../utils/index.mjs";
let totalLockCount = 0;
const BODY_LOCK_CLASS = "van-overflow-hidden";
// 是否锁定背景滚动 锁定主页面不能scroll 滑动时父节点也不能滚动
// rootRef为dialog节点, shouldLock为是有锁定compute函数
function useLockScroll(rootRef, shouldLock) {
  const touch = useTouch();
  const DIRECTION_UP = "01";
  const DIRECTION_DOWN = "10";
  const onTouchMove = (event) => {
    touch.move(event);
    const direction = touch.deltaY.value > 0 ? DIRECTION_DOWN : DIRECTION_UP;
    const el = getScrollParent(
      event.target,
      rootRef.value
    );
    const { scrollHeight, offsetHeight, scrollTop } = el;
    let status = "11";
    if (scrollTop === 0) {
      status = offsetHeight >= scrollHeight ? "00" : "01";
    } else if (scrollTop + offsetHeight >= scrollHeight) {
      status = "10";
    }
    // 根据计算量 判断是否阻止默认事件
    if (status !== "11" && touch.isVertical() && !(parseInt(status, 2) & parseInt(direction, 2))) {
      preventDefault(event, true);
    }
  };
  // 添加body禁止scroll及全局touch监听
  const lock = () => {
    document.addEventListener("touchstart", touch.start);
    document.addEventListener("touchmove", onTouchMove, { passive: false });
    // 无时添加body对应class
    if (!totalLockCount) {
      document.body.classList.add(BODY_LOCK_CLASS);
    }
    totalLockCount++;
  };
  const unlock = () => {
    if (totalLockCount) {
      document.removeEventListener("touchstart", touch.start);
      document.removeEventListener("touchmove", onTouchMove);
      totalLockCount--;
      // totalLockCount全部移除是,移除对应class
      if (!totalLockCount) {
        document.body.classList.remove(BODY_LOCK_CLASS);
      }
    }
  };
  // 各个生命周期shouldLock为true直接lock 及 状态改变时  打开关闭对应锁
  // shouldLock为true触发的限制
  const init = () => shouldLock() && lock();
  const destroy = () => shouldLock() && unlock();
  onMountedOrActivated(init);
  onDeactivated(destroy);
  onBeforeUnmount(destroy);
  watch(shouldLock, (value) => {
    value ? lock() : unlock();
  });
}
export {
  useLockScroll
};
